<template>
  <view class="task-assign-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="content">任务分配</block>
      <block slot="right">
        <text class="cuIcon-check" @click="confirmAssign"></text>
      </block>
    </cu-custom>

    <!-- 任务信息 -->
    <view class="task-info bg-white margin-top">
      <view class="info-header padding">
        <text class="info-title">任务信息</text>
      </view>
      <view class="info-content padding">
        <view class="task-title">{{ taskInfo.title }}</view>
        <view class="task-meta margin-top-sm">
          <text class="text-sm text-gray">计划：{{ taskInfo.planName }}</text>
          <text class="text-sm text-gray margin-left">工种：{{ taskInfo.workType }}</text>
        </view>
        <view class="task-desc margin-top-sm text-sm">{{ taskInfo.description }}</view>
        <view class="task-time margin-top-sm">
          <text class="text-sm text-gray">预计时间：{{ taskInfo.estimatedHours }}小时</text>
          <text class="text-sm text-gray margin-left">截止时间：{{ formatTime(taskInfo.deadline) }}</text>
        </view>
      </view>
    </view>

    <!-- 员工选择 -->
    <view class="employee-selection bg-white margin-top">
      <view class="selection-header padding">
        <text class="selection-title">选择员工</text>
        <text class="filter-btn" @click="showFilterModal = true">筛选</text>
      </view>
      
      <!-- 搜索栏 -->
      <view class="search-bar padding-lr">
        <view class="search-input-wrapper">
          <input v-model="searchKeyword" 
                 placeholder="搜索员工姓名" 
                 class="search-input" 
                 @input="onSearch" />
          <text class="cuIcon-search search-icon"></text>
        </view>
      </view>

      <!-- 员工列表 -->
      <view class="employee-list">
        <view v-for="employee in filteredEmployees" :key="employee.id" 
              class="employee-item padding border-bottom"
              :class="{ selected: selectedEmployee && selectedEmployee.id === employee.id }"
              @click="selectEmployee(employee)">
          <view class="flex align-center">
            <image :src="employee.avatar || '/static/images/default-avatar.png'" 
                   class="employee-avatar margin-right"></image>
            <view class="flex-sub">
              <view class="employee-name">{{ employee.name }}</view>
              <view class="employee-info text-sm text-gray">
                工号：{{ employee.employeeNo }} | {{ employee.department }}
              </view>
              <view class="employee-skills margin-top-xs">
                <text v-for="skill in employee.workTypes" :key="skill" 
                      class="skill-tag">{{ skill }}</text>
              </view>
            </view>
            <view class="employee-metrics">
              <view class="metric-item">
                <text class="metric-label text-xs text-gray">当前任务</text>
                <text class="metric-value text-sm">{{ employee.currentTasks }}</text>
              </view>
              <view class="metric-item margin-top-xs">
                <text class="metric-label text-xs text-gray">完成率</text>
                <text class="metric-value text-sm text-green">{{ employee.completionRate }}%</text>
              </view>
            </view>
            <view v-if="selectedEmployee && selectedEmployee.id === employee.id" class="selected-icon">
              <text class="cuIcon-check text-blue"></text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 分配设置 -->
    <view class="assign-settings bg-white margin-top margin-bottom">
      <view class="settings-header padding">
        <text class="settings-title">分配设置</text>
      </view>
      <view class="settings-content padding">
        <view class="form-item margin-bottom">
          <text class="form-label">优先级</text>
          <picker :range="priorityOptions" 
                  range-key="label"
                  :value="selectedPriorityIndex"
                  @change="onPriorityChange">
            <view class="form-picker">
              {{ assignForm.priority ? (priorityOptions[selectedPriorityIndex] && priorityOptions[selectedPriorityIndex].label) : '请选择优先级' }}
              <text class="cuIcon-right"></text>
            </view>
          </picker>
        </view>
        
        <view class="form-item margin-bottom">
          <text class="form-label">开始时间</text>
          <picker mode="datetime" 
                  :value="assignForm.startTime" 
                  @change="onStartTimeChange">
            <view class="form-picker">
              {{ assignForm.startTime || '请选择开始时间' }}
              <text class="cuIcon-right"></text>
            </view>
          </picker>
        </view>
        
        <view class="form-item margin-bottom">
          <text class="form-label">备注</text>
          <textarea v-model="assignForm.remark" 
                    placeholder="请输入分配备注" 
                    class="form-textarea"></textarea>
        </view>
      </view>
    </view>

    <!-- 筛选弹窗 -->
    <view v-if="showFilterModal" class="filter-modal" @click="showFilterModal = false">
      <view class="filter-content" @click.stop>
        <view class="filter-header padding">
          <text class="text-lg text-bold">筛选条件</text>
          <text class="cuIcon-close float-right" @click="showFilterModal = false"></text>
        </view>
        <view class="filter-form padding">
          <view class="form-item margin-bottom">
            <text class="form-label">工种要求</text>
            <picker :range="workTypeOptions" 
                    :value="filterForm.workTypeIndex"
                    @change="onFilterWorkTypeChange">
              <view class="form-picker">
                {{ filterForm.workType || '不限' }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
          
          <view class="form-item margin-bottom">
            <text class="form-label">工作状态</text>
            <picker :range="statusOptions" 
                    :value="filterForm.statusIndex"
                    @change="onFilterStatusChange">
              <view class="form-picker">
                {{ filterForm.status || '不限' }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
        </view>
        <view class="filter-actions padding">
          <button class="cu-btn bg-gray margin-right" @click="resetFilter">重置</button>
          <button class="cu-btn bg-blue" @click="applyFilter">确定</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      taskInfo: {},
      searchKeyword: '',
      selectedEmployee: null,
      employees: [],
      filteredEmployees: [],
      showFilterModal: false,
      assignForm: {
        priority: '',
        startTime: '',
        remark: ''
      },
      filterForm: {
        workType: '',
        workTypeIndex: 0,
        status: '',
        statusIndex: 0
      },
      priorityOptions: [
        { label: '低优先级', value: 'low' },
        { label: '中优先级', value: 'medium' },
        { label: '高优先级', value: 'high' }
      ],
      selectedPriorityIndex: 1,
      workTypeOptions: ['不限', '切割', '组装', '打包', '质检', '喷涂', '焊接'],
      statusOptions: ['不限', '空闲', '忙碌']
    }
  },

  onLoad(options) {
    if (options.taskId) {
      this.loadTaskInfo(options.taskId)
    }
    if (options.employeeId) {
      this.preSelectEmployee(options.employeeId)
    }
    this.loadEmployees()
  },

  methods: {
    loadTaskInfo(taskId) {
      // 模拟任务数据
      this.taskInfo = {
        id: taskId,
        title: '门框切割任务',
        planName: '订单WK001生产计划',
        workType: '切割',
        description: '按照图纸要求切割铝合金门框，注意尺寸精度',
        estimatedHours: 4,
        deadline: '2024-03-01 18:00:00'
      }
    },

    loadEmployees() {
      // 模拟员工数据
      this.employees = [
        {
          id: 1,
          name: '张三',
          employeeNo: 'EMP001',
          department: '生产部',
          avatar: '',
          workTypes: ['切割', '组装'],
          currentTasks: 2,
          completionRate: 95,
          status: 'idle'
        },
        {
          id: 2,
          name: '李四',
          employeeNo: 'EMP002',
          department: '生产部',
          avatar: '',
          workTypes: ['切割', '打包'],
          currentTasks: 1,
          completionRate: 88,
          status: 'idle'
        },
        {
          id: 3,
          name: '王五',
          employeeNo: 'EMP003',
          department: '生产部',
          avatar: '',
          workTypes: ['组装', '质检'],
          currentTasks: 3,
          completionRate: 92,
          status: 'busy'
        }
      ]
      
      this.filterEmployees()
    },

    preSelectEmployee(employeeId) {
      const employee = this.employees.find(e => e.id == employeeId)
      if (employee) {
        this.selectedEmployee = employee
      }
    },

    onSearch() {
      this.filterEmployees()
    },

    filterEmployees() {
      let filtered = this.employees

      // 搜索过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase()
        filtered = filtered.filter(employee => 
          employee.name.toLowerCase().includes(keyword)
        )
      }

      // 工种过滤
      if (this.filterForm.workType && this.filterForm.workType !== '不限') {
        filtered = filtered.filter(employee => 
          employee.workTypes.includes(this.filterForm.workType)
        )
      }

      // 状态过滤
      if (this.filterForm.status && this.filterForm.status !== '不限') {
        const statusMap = { '空闲': 'idle', '忙碌': 'busy' }
        filtered = filtered.filter(employee => 
          employee.status === statusMap[this.filterForm.status]
        )
      }

      this.filteredEmployees = filtered
    },

    selectEmployee(employee) {
      this.selectedEmployee = employee
    },

    onPriorityChange(e) {
      this.selectedPriorityIndex = e.detail.value
      this.assignForm.priority = this.priorityOptions[e.detail.value].value
    },

    onStartTimeChange(e) {
      this.assignForm.startTime = e.detail.value
    },

    onFilterWorkTypeChange(e) {
      this.filterForm.workTypeIndex = e.detail.value
      this.filterForm.workType = this.workTypeOptions[e.detail.value]
    },

    onFilterStatusChange(e) {
      this.filterForm.statusIndex = e.detail.value
      this.filterForm.status = this.statusOptions[e.detail.value]
    },

    resetFilter() {
      this.filterForm = {
        workType: '',
        workTypeIndex: 0,
        status: '',
        statusIndex: 0
      }
      this.filterEmployees()
    },

    applyFilter() {
      this.showFilterModal = false
      this.filterEmployees()
    },

    async confirmAssign() {
      if (!this.selectedEmployee) {
        uni.showToast({
          title: '请选择员工',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({ title: '分配中...' })
        
        // 模拟分配
        setTimeout(() => {
          uni.hideLoading()
          uni.showToast({
            title: '分配成功',
            icon: 'success'
          })
          
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }, 1500)
        
      } catch (error) {
        console.error('分配失败:', error)
        uni.showToast({
          title: '分配失败',
          icon: 'none'
        })
      }
    },

    formatTime(timeStr) {
      if (!timeStr) return '--'
      const date = new Date(timeStr)
      return `${date.getMonth() + 1}/${date.getDate()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
.task-assign-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.task-info,
.employee-selection,
.assign-settings {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .info-header,
  .selection-header,
  .settings-header {
    border-bottom: 1rpx solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .info-title,
    .selection-title,
    .settings-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .filter-btn {
      font-size: 28rpx;
      color: #1890ff;
    }
  }
  
  .task-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.search-bar {
  .search-input-wrapper {
    position: relative;
    
    .search-input {
      width: 100%;
      height: 80rpx;
      padding: 0 60rpx 0 24rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
    
    .search-icon {
      position: absolute;
      right: 24rpx;
      top: 50%;
      transform: translateY(-50%);
      color: #999;
    }
  }
}

.employee-list {
  max-height: 600rpx;
  overflow-y: auto;
  
  .employee-item {
    &.selected {
      background-color: #e6f7ff;
    }
    
    .employee-avatar {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
    }
    
    .employee-name {
      font-size: 28rpx;
      font-weight: bold;
      margin-bottom: 4rpx;
    }
    
    .employee-skills {
      display: flex;
      flex-wrap: wrap;
      gap: 8rpx;
      
      .skill-tag {
        padding: 2rpx 8rpx;
        background-color: #e6f7ff;
        color: #1890ff;
        border-radius: 8rpx;
        font-size: 20rpx;
      }
    }
    
    .employee-metrics {
      text-align: right;
      
      .metric-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        min-width: 120rpx;
        
        .metric-label {
          margin-right: 8rpx;
        }
      }
    }
    
    .selected-icon {
      font-size: 32rpx;
      margin-left: 16rpx;
    }
  }
}

.assign-settings {
  .form-item {
    .form-label {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 16rpx;
    }
    
    .form-picker {
      height: 80rpx;
      padding: 0 24rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #333;
    }
    
    .form-textarea {
      width: 100%;
      min-height: 120rpx;
      padding: 16rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
      resize: none;
    }
  }
}

.filter-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .filter-content {
    background-color: white;
    border-radius: 12rpx;
    margin: 0 48rpx;
    width: calc(100% - 96rpx);
    max-height: 80vh;
    overflow: hidden;
    
    .filter-header {
      border-bottom: 1rpx solid #f0f0f0;
      position: relative;
      
      .cuIcon-close {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        font-size: 32rpx;
        color: #999;
      }
    }
    
    .filter-form {
      .form-item {
        .form-label {
          display: block;
          font-size: 28rpx;
          color: #333;
          margin-bottom: 16rpx;
        }
        
        .form-picker {
          height: 80rpx;
          padding: 0 24rpx;
          border: 1rpx solid #d9d9d9;
          border-radius: 8rpx;
          font-size: 28rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          color: #333;
        }
      }
    }
    
    .filter-actions {
      border-top: 1rpx solid #f0f0f0;
      display: flex;
      gap: 16rpx;
      
      .cu-btn {
        flex: 1;
      }
    }
  }
}
</style>
